<template>
  <el-autocomplete
    placeholder="请点击"
    :fetch-suggestions="querySearchAsync"
    :value-key="props.valueKey"
  />
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref } from "vue";

const props = defineProps<{ valueKey: string }>();

const emit = defineEmits<{
  (
    e: "get-record",
    callback: (records: Record<string, string>[]) => void
  ): void;
}>();

let records = ref<Record<string, string>[]>([]);

const getRecord = () => {
  emit("get-record", (value: Record<string, string>[]) => {
    records.value = value;
  });
};
getRecord();

const querySearchAsync = (
  queryString: string,
  callback: (arg: Record<string, string>[]) => void
) => {
  const results = queryString
    ? (records.value.filter((record) => {
        return (
          record[props.valueKey]
            .toLowerCase()
            .indexOf(queryString.toLowerCase()) === 0
        );
      }) as Record<string, string>[])
    : (records.value as Record<string, string>[]);
  setTimeout(() => {
    callback(results);
  }, 0);
};
</script>
<style scoped></style>
